'use strict';

const Command = require('@duo-cli/command');
const fs = require('fs');
const fse = require('fs-extra');
const inquirer = require('inquirer');
const semver = require('semver'); 
const log = require("@duo-cli/log");

const TYPE_PROJECT = "project";
const TYPE_COMPONENT = "component";

class InitCommand extends Command {
    init() {
        this.projectName = this._argv[0] || '';
        this.force = this._argv[1].force || false;
        log.verbose("init_projectName", this.projectName);
        log.verbose("init_force", this.force);
    } 

    async exec() {
        try {
            //准备阶段
            const projectInfo = await this.prepare();
            if (projectInfo) {
                log.verbose("projectInfo", projectInfo);
                //下载模板
                this.downloadTemplate()
                //安装模板
            }
        } catch (error) {
            console.log(error.message)
        }
    }

    downloadTemplate() {
        
    }

    async prepare() {
        const localPath = process.cwd();
        // 判断当前目录是否为空
        if (!this.isDirEmpty(localPath)) {
            let ifContinue = false;
            if (!this.force) {
                //询问是否继续创建
                ifContinue =
                    (await inquirer.prompt([
                        {
                            type: 'confirm',
                            name: 'ifContinue',
                            message: '当前文件夹不为空，是否继续创建项目?',
                            default: false
                        },
                    ])).ifContinue;
                if (!ifContinue) {
                    return;
                }
            }
            if (ifContinue || this.force) {
                //清空前的二次确认
                const {confirmDelete} = await inquirer.prompt([{
                    type: 'confirm',
                    name: 'confirmDelete',
                    default: false,
                    message: "是否确认清空当前目录下的文件夹"
                }])
                if (confirmDelete) {
                    fse.emptyDirSync(localPath);
                }
            }
        }
        return this.getProjectInfo()
    }

    async getProjectInfo() {
        let projectInfo = {};
        const { type } = await inquirer.prompt([{
            type: 'list',
            name: 'type',
            default: TYPE_PROJECT,
            message: "请选择初始化类型",
            choices: [
                {name: "项目", value: TYPE_PROJECT},
                {name: "组件", value: TYPE_COMPONENT}
            ]
        }])

        if (TYPE_PROJECT === type) {
            const project = await inquirer.prompt([{
                type: 'input',
                name: 'projectName',
                default: '',
                message: "请输入项目名称",
                validate: function(v) {
                    const done = this.async();
                    setTimeout(function() {
                        if (!/^[a-zA-Z]+([-][a-zA-Z][a-zA-Z0-9]*|[_][a-zA-Z][a-zA-Z0-9]*|[a-zA-Z0-9])*$/.test(v)) {
                            done('请输入合法的项目名称');
                        } else {
                            done(null, true);
                        }
                    }, 0);
                },
                filter: function(v) {
                    return v;
                }, 
            },{
                type: 'input',
                name: 'projectVersion',
                default: '',
                message: "请输入项目版本号",
                validate: function(v) {
                    const done = this.async();
                    setTimeout(function() {
                        if (!semver.valid(v)) {
                            done('请输入合法的版本号');
                        } else {
                            done(null, true);
                        }
                    }, 0);
                },
                filter: function(v) {
                    if (!!semver.valid(v)) {
                        return semver.valid(v);
                    } else {
                        return v
                    }
                }, 
            }])
            projectInfo = {
                type,
                ...project
            }
        } else if (TYPE_COMPONENT === type) {

        }

        return projectInfo;
    }

    isDirEmpty(localPath) {
        let fileList = fs.readdirSync(localPath)
        fileList = fileList.filter((file) =>
            (!file.startsWith('.') && ['node_modules'].indexOf(file) < 0)
        )
        return !fileList || fileList.length <= 0
    }
}

function init(argv) {
    return new InitCommand(argv);
}
module.exports = init;
module.exports.InitCommand = InitCommand;
